package com.LeetCode.dp.Array;

import org.junit.Test;

/**
 * 最大乘积子数组
 */
public class MaxMultArray {

    public int maxProduct(int[] nums) {
        int max = 1;
        int min = 1;
        int res = Integer.MIN_VALUE;
        for(int num : nums){
            if(num < 0){
                int tmp = max; max = min; min = tmp;
            }

            max = Math.max(max * num , num);
            min = Math.min(min * num , num);

            res = Math.max(res, max);
        }
        return res;
    }

    public double maxProduct_double(double[] arr){
        if(arr.length == 0)
            return 0;

        double maxpre = arr[0];
        double minpre = arr[0];
        double max = arr[0];

        double maxhere, minhere;

        for(int i = 1; i<arr.length; i++){
            maxhere = Math.max(arr[i], Math.max(maxpre * arr[i], minpre * arr[i]));
            minhere = Math.min(arr[i], Math.min(maxpre * arr[i], minpre * arr[i]));
            max = Math.max(maxhere, max);
            maxpre = maxhere;
            minpre = minhere;
        }
        return max;
    }

    @Test
    public void test(){
        int[] arr = {2,3,-2,4};
        System.out.println(maxProduct(arr));
    }

    @Test
    public void testDouble(){
        double[] arr = {-2.5, 4, 0, 3, 0.5, 8, -1};
        System.out.println(maxProduct_double(arr));
    }
}
